package cn.drenal.capcap.service.impl;

import cn.drenal.capcap.entity.Artwork;
import cn.drenal.capcap.entity.Comment;
import cn.drenal.capcap.entity.vo.CommentListVO;
import cn.drenal.capcap.exception.BizException;
import cn.drenal.capcap.mapper.ArtworkMapper;
import cn.drenal.capcap.mapper.CommentMapper;
import cn.drenal.capcap.mapper.UserMapper;
import cn.drenal.capcap.service.ArtworkService;
import cn.drenal.capcap.service.CommentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 评论服务实现类
 */
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    private final ArtworkMapper artworkMapper;
    private final UserMapper userMapper;

    @Override
    @Transactional
    public Comment createComment(Comment comment) {
        // 检查作品是否存在
        Artwork artwork = artworkMapper.selectById(comment.getArtworkId());
        if (artwork == null) {
            throw new BizException("作品不存在");
        }
        
        // 设置默认值
        if (comment.getLikeCount() == null) {
            comment.setLikeCount(0);
        }
        if (comment.getStatus() == null) {
            comment.setStatus(0); // 默认待审核
        }
        
        // 保存评论
        save(comment);
        
        // 更新作品评论数
        artwork.setCommentCount(artwork.getCommentCount() + 1);
        artworkMapper.updateById(artwork);
        
        return comment;
    }

    @Override
    public Comment updateComment(Long id, Comment comment) {
        // 检查评论是否存在
        Comment existingComment = getById(id);
        if (existingComment == null) {
            throw new BizException("评论不存在");
        }
        
        // 只允许更新内容和状态
        existingComment.setContent(comment.getContent());
        if (comment.getStatus() != null) {
            existingComment.setStatus(comment.getStatus());
        }
        
        updateById(existingComment);
        return existingComment;
    }

    @Override
    @Transactional
    public void deleteComment(Long id) {
        // 检查评论是否存在
        Comment comment = getById(id);
        if (comment == null) {
            throw new BizException("评论不存在");
        }
        
        // 删除评论
        removeById(id);
        
        // 更新作品评论数
        Artwork artwork = artworkMapper.selectById(comment.getArtworkId());
        artwork.setCommentCount(artwork.getCommentCount() - 1);
        artworkMapper.updateById(artwork);
    }

    @Override
    public Comment getCommentById(Long id) {
        Comment comment = getById(id);
        if (comment == null) {
            throw new BizException("评论不存在");
        }
        return comment;
    }

    @Override
    public Page<CommentListVO> getCommentPage(Page<Comment> page, String content, String artworkName, String username, Integer status) {
        // 创建查询条件
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        
        // 根据评论内容模糊查询
        if (content != null && !content.isEmpty()) {
            queryWrapper.like(Comment::getContent, content);
        }
        
        // 根据状态精确查询
        if (status != null) {
            queryWrapper.eq(Comment::getStatus, status);
        }
        
        // 先查询所有评论
        page = page(page, queryWrapper);
        
        // 转换为VO对象并进行二次筛选
        Page<CommentListVO> voPage = new Page<>();
        BeanUtils.copyProperties(page, voPage);
        
        // 处理记录并进行二次筛选
        voPage.setRecords(page.getRecords().stream()
            .map(comment -> {
                CommentListVO vo = new CommentListVO();
                BeanUtils.copyProperties(comment, vo);
                
                // 获取作品名称
                Artwork artwork = artworkMapper.selectById(comment.getArtworkId());
                String title = artwork != null ? artwork.getTitle() : "";
                vo.setArtworkName(title);
                
                // 获取用户名
                String userNickname = userMapper.selectById(comment.getUserId()).getUsername();
                vo.setUsername(userNickname);
                
                return vo;
            })
            // 根据作品名称筛选
            .filter(vo -> artworkName == null || artworkName.isEmpty() || 
                    vo.getArtworkName().contains(artworkName))
            // 根据用户名筛选
            .filter(vo -> username == null || username.isEmpty() || 
                    vo.getUsername().contains(username))
            .toList());
        
        // 重新计算总记录数
        voPage.setTotal(voPage.getRecords().size());
        
        return voPage;
    }

    @Override
    public Comment reviewComment(Long id, Integer status, String remark) {
        // 检查评论是否存在
        Comment comment = getById(id);
        if (comment == null) {
            throw new BizException("评论不存在");
        }
        
        // 检查状态是否有效
        if (status < 0 || status > 2) { // 0-待审核，1-已通过，2-已拒绝
            throw new BizException("无效的审核状态");
        }
        
        // 当状态为已拒绝时，审核意见必填
        if (status == 2 && (remark == null || remark.trim().isEmpty())) {
            throw new BizException("拒绝时必须填写审核意见");
        }
        
        // 更新状态和审核意见
        comment.setStatus(status);
        comment.setRemark(status == 2 ? remark : null); // 只有拒绝时才设置审核意见
        updateById(comment);
        
        return comment;
    }

    @Override
    public Page<Comment> getCommentsByArtworkId(Long artworkId, Page<Comment> page) {
        // 检查作品是否存在
        Artwork artwork = artworkMapper.selectById(artworkId);
        if (artwork == null) {
            throw new BizException("作品不存在");
        }
        
        // 只查询已通过审核的评论
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getArtworkId, artworkId)
                .eq(Comment::getStatus, 1) // 1-已通过
                .orderByDesc(Comment::getCreateTime);
        
        return page(page, queryWrapper);
    }

    @Override
    public void likeComment(Long id) {
        // 检查评论是否存在
        if (!lambdaQuery().eq(Comment::getId, id).exists()) {
            throw new BizException("评论不存在");
        }
        
        // 增加点赞数
        lambdaUpdate()
                .eq(Comment::getId, id)
                .setSql("like_count = like_count + 1")
                .update();
    }
}